<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>案例5_表格全选</title>
    <style>
        table {
            width: 500px;
            border: 1px solid;
            margin-left: 30%;
        }

        td, th {
            text-align: center;
            border: 1px solid;
        }

        div {
            margin-top: 10px;
            margin-left: 30%;
        }
    </style>
</head>
<body>

<table>

    <caption>学生信息表</caption>
    <tr>
        <th></th>
        <th>编号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>操作</th>
    </tr>
    <tr>
        <td><input type="checkbox" name="cb"></td>
        <td>1</td>
        <td>令狐冲</td>
        <td>男</td>
        <td><a href="javascript:void(0);">删除</a></td>
    </tr>

    <tr>
        <td><input type="checkbox" name="cb"></td>
        <td>2</td>
        <td>任我行</td>
        <td>男</td>
        <td><a href="javascript:void(0);">删除</a></td>
    </tr>

    <tr>
        <td><input type="checkbox" name="cb"></td>
        <td>3</td>
        <td>岳不群</td>
        <td>?</td>
        <td><a href="javascript:void(0);">删除</a></td>
    </tr>

</table>

<div>
    <input type="button" id="selectAll" value="全选">
    <input type="button" id="unSelectAll" value="全不选">
    <input type="button" id="selectRev" value="反选">
</div>

</body>

</html>

<script>
    let selectAllElement = document.getElementById("selectAll");
    let unSelectAllElement = document.getElementById("unSelectAll");
    let selectRevElement = document.getElementById("selectRev");
    let checkBoxElements = document.getElementsByName("cb");
    let trElements = document.getElementsByTagName("tr");

    selectAllElement.onclick = selectAll;
    unSelectAllElement.onclick = unSelectAll;
    selectRevElement.onclick = function () {
        checkBoxElements.forEach(function (item) {
            item.checked = !item.checked;
        });
    };

    for (let trElement of trElements) {
        trElement.onmouseover = function () {
            this.style.backgroundColor = "pink";
        };
        trElement.onmouseout = function () {
            this.style.backgroundColor = "white";
        };
    }

    function selectAll() {
        checkBoxElements.forEach(function (item) {
            item.checked = true;
        });
    }

    function unSelectAll() {
        for (let element of checkBoxElements) {
            element.checked = false;
        }
    }

</script>